package com.top.horizon.th1804app.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.net.protocol.model.CommonModel;
import com.top.horizon.th1804app.R;
import com.top.horizon.th1804app.base.BaseActivity;
import com.top.horizon.th1804app.constant.Constant;
import com.net.protocol.NetController;
import com.top.horizon.th1804app.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class LoginActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private EditText etAccounts, etPassword;
    private CheckBox cbRememberPassword;
    private String name;
    private String passWord;
    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {

        }
    };

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        //帐号输入框
        etAccounts = findViewById(R.id.et_accounts);
        //密码输入框
        etPassword = findViewById(R.id.et_password);
        //记住密码选择框
        cbRememberPassword = findViewById(R.id.cb_remember_password);
        //以下为注册点击监听
        findViewById(R.id.tv_forget_password).setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        cbRememberPassword.setOnCheckedChangeListener(this);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {

        String userName = (String) SPUtils.get(this, Constant.USER_NAME, "");
        String pwd = (String) SPUtils.get(this, Constant.PASSWORD, "");
        boolean isRememberPassword = (boolean) SPUtils.get(this, Constant.IS_REMEMBER_PASSWORD, false);

        cbRememberPassword.setChecked(isRememberPassword);
        etAccounts.setText(userName);
        etPassword.setText(isRememberPassword ? pwd : "");
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commonEvent(CommonModel commonAck){
        hideProressDialog();
        if (commonAck.code == 0) {
            //验证通过，缓存帐号，然后直接打开MainActivity界面
            SPUtils.put(this, Constant.USER_NAME, name);
            SPUtils.put(this, Constant.PASSWORD, passWord);
            skinMainActivity();
        }else {
            showToast("账号密码错误");
        }
    }

    /**
     * 忘记密码和登录按钮点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_forget_password:
                //点击忘记密码的事件
                showChooseDialog(R.layout.dialog_forget_password);
                break;
            case R.id.btn_login:
                //点击登录按钮事件
                String userName = etAccounts.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                //检查用户名是否正确
//                Pattern namePattern = Pattern.compile(Constant.REG_USER_NAME);
//                Matcher nameMatcher = namePattern.matcher(userName);
                //判断用户名是否为空
                if (!TextUtils.isEmpty(userName)) {
                    //判断用户名是否满足正则
                    if (userName.length() > 4 && userName.length() < 20) {
                        //验证密码是否为空
                        if (!TextUtils.isEmpty(password)) {
//                            Pattern pwdPattern = Pattern.compile(Constant.REG_USER_PWD);
//                            Matcher pwdMatcher = pwdPattern.matcher(password);
                            if (/*pwdMatcher.find() &&*/ password.length() > 4 && password.length() < 20) {
                                //通过后想服务器发送请求，验证帐号和密码是否正确
                                goServiceLogin(userName, password);
                            } else {
                                showToast("密码应为4到20之间的英文字符或数字！");
                            }
                        } else {
                            showToast("密码不能为空！");
                        }
                    } else {
                        showToast("用户名应为4到20之间的英文字符！");
                    }

                } else {
                    showToast("用户名不能为空！");
                }
                break;
        }
    }


    /**
     * 去服务器验证登录  返回登录成功后直接进去到主界面
     *
     * @param userName
     * @param pwd
     */
    private void goServiceLogin(String userName, String pwd) {
        name = userName;
        passWord = pwd;
        showProgressDialog("加载中");
        int login = NetController.login(userName, pwd);
        //test begin
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new CommonModel());
            }
        },2_000);
        //test end
    }

    /**
     * 记住密码改变监听
     *
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        SPUtils.put(this, Constant.IS_REMEMBER_PASSWORD, isChecked);
    }

    private void skinMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    /**
     * 点击对话框内view事件
     *
     * @param view
     * @param mLayoutId
     */
    @Override
    public void onClickChildView(View view, int mLayoutId) {
        view.findViewById(R.id.btn_forget_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissDialog();
            }
        });

    }
}
